package com.glasses.business.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.glasses.business.R;
import com.glasses.business.activity.WebDetailActiviy;
import com.glasses.business.adapter.GlassFrameAdapter;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.AppBaseFragment;
import com.glasses.business.base.MyBaseAdapter;
import com.glasses.business.entity.GlassDetail;
import com.glasses.business.event.BussEvent;
import com.glasses.business.http.NetUtils;
import com.glasses.business.utils.Tools;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.neiquan.applibrary.wight.RefreshLayout;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.ToastUtil;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/7
 * Version：1.0
 */

public class GlassFrameFragment extends AppBaseFragment implements RefreshLayout.RetryListener, XRecyclerView.LoadingListener {

    @InjectView(R.id.priceUp)
    TextView priceUp;
    @InjectView(R.id.priceDown)
    TextView priceDown;
    @InjectView(R.id.filterSort)
    TextView filterSort;
    @InjectView(R.id.recyclerview)
    XRecyclerView mRecyclerview;
    @InjectView(R.id.refesh_ly)
    RefreshLayout mRefeshLy;
    private GlassFrameAdapter glassFrameAdapter;
    private RecyclerView mRecylerView_;
    private int pageNum = 0;
    private int PAEG_SIZE = 10;
    private List<GlassDetail> list;
    private int type = -1;
    private int sort = 0;
    private String select = "";

    @Override
    public int getRootViewId() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return R.layout.fragment_glass_frame;
    }

    public void onEventMainThread(BussEvent event) {
        if (event.getState() == BussEvent.Fiflter) {
            select = (String) event.getMessage();
            onRefresh();
        } else if (event.getState() == BussEvent.Product0) {
            MyApplication.getInstance().manager.onBackPressed();
//            BussEvent event1 = new BussEvent(BussEvent.Product1);
//            EventBus.getDefault().post(event1);
        }
    }

    @Override
    public void setViews() {
        glassFrameAdapter = new GlassFrameAdapter(getActivity(), null);
        mRecyclerview.setAdapter(glassFrameAdapter);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setOrientation(StaggeredGridLayoutManager.VERTICAL);
        mRecyclerview.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerview.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerview.setArrowImageView(R.mipmap.iconfont_downgrey);
        mRecyclerview.setHasFixedSize(true);
        mRecyclerview.setLayoutManager(layoutManager);
        mRefeshLy.setRetryListener(this);

        mRecyclerview.setLoadingListener(this);
        mRecyclerview.setLoadingMoreEnabled(false);
        mRecyclerview.setPullRefreshEnabled(true);
        glassFrameAdapter.setOnItemClickListener(new MyBaseAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, List data, int position) {
                GlassDetail glassDetail = (GlassDetail) data.get(position);
                Bundle bundle = new Bundle();
                bundle.putInt("id", glassDetail.getId());
                bundle.putInt("type", 0);
                open(new GlassDetailFragment(), bundle);
            }
        });
    }

    @Override
    public void initData() {
        setTitleTv("镜架列表");
        setNextTv("选镜须知");
        if (getArguments() != null) {
            type = getArguments().getInt("type");
        }
        setNextOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Tools.showDialog(getActivity());
                NetUtils.getInstance().systemContent(3, new NetCallBack() {
                    @Override
                    public void onSuccess(String response, String mssage, ResultModel model) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast(mssage);
                        Bundle bundle = new Bundle();
                        bundle.putString("title", "选镜须知");
                        bundle.putString("url", response);
                        Intent intent = new Intent(getActivity(), WebDetailActiviy.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }

                    @Override
                    public void onFail(boolean dataError, int errorCode, String mssage) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast(mssage);
                    }
                }, null);
            }
        });
        loadDatas(true);
    }

    private void loadDatas(final boolean isRefush) {
        Tools.showDialog(getActivity());
        NetUtils.getInstance().product0List(pageNum, PAEG_SIZE, select, sort, type, new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                mRecyclerview.loadMoreComplete();
                mRecyclerview.refreshComplete();
                mRefeshLy.hideAll();
                list = (List<GlassDetail>) model.getModelList();
                if (isRefush) {
                    glassFrameAdapter.clear();
                }
                glassFrameAdapter.append(list);
                if (list == null || list.size() < 10) {
                    if (isRefush && (list == null || list.size() == 0)) {
//                        mRefeshLy.showEmptyView();
                        mRefeshLy.showFailView();
                    }
                    mRecyclerview.setLoadingMoreEnabled(false);
                } else {
                    mRecyclerview.setLoadingMoreEnabled(true);
                }
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                //                mRefeshLy.hideAll();
                mRefeshLy.showFailView();
                mRecyclerview.loadMoreComplete();
                mRecyclerview.refreshComplete();
            }
        }, GlassDetail.class);
    }

    @Override
    public boolean mainTabShow() {
        return false;
    }


    @OnClick({R.id.priceUp, R.id.priceDown, R.id.filterSort})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.priceUp:
                sort = 0;
                select = "";
                changeTextColor(priceUp, priceDown, filterSort);
                onRefresh();
                break;
            case R.id.priceDown:
                sort = 1;
                select = "";
                changeTextColor(priceDown, priceUp, filterSort);
                onRefresh();
                break;
            case R.id.filterSort:
                sort = -1;
                changeTextColor(filterSort, priceDown, priceUp);
                open(new GlassFrameFilterFragment());
                break;
        }
    }

    @Override
    public void onRetryClick() {
        pageNum = 0;
        loadDatas(true);
    }

    @Override
    public void onRefresh() {
        pageNum = 0;
        loadDatas(true);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        loadDatas(false);
    }


    private void changeTextColor(TextView mTv1, TextView mTv2, TextView mTv3) {
        mTv1.setTextColor(getResources().getColor(R.color.red));
        mTv2.setTextColor(getResources().getColor(R.color.text_gray));
        mTv3.setTextColor(getResources().getColor(R.color.text_gray));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        EventBus.getDefault().unregister(this);
    }
}
